package com.bjpowernode.web;

import com.alibaba.excel.EasyExcel;
import com.bjpowernode.model.TCustomer;
import com.bjpowernode.query.CustomerQuery;
import com.bjpowernode.result.CustomerExcel;
import com.bjpowernode.result.R;
import com.bjpowernode.service.CustomerService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
public class CustomerController {

    @Resource
    private CustomerService customerService;

    /**
     * 数据导出到Excel
     */
    @GetMapping(value = "/api/exportExcel")
    public void exportExcel(HttpServletResponse response, @RequestParam(value = "ids", required = false) String ids) {
        // 要让浏览器弹出下载框,需要设置一下响应头信息
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + new Date().getTime() + ".xlsx");

        // 后端查询数据库的数据,把数据写入Excel,然后把Excel以流的方式输出到前端浏览器
        try {
            List<CustomerExcel> dataList = customerService.getCustomerByExcel(ids);
            EasyExcel.write(response.getOutputStream(), CustomerExcel.class)
                    .sheet()
                    .doWrite(dataList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 客户管理列表分页
     * @param current
     * @return
     */
    @GetMapping(value = "/api/customers")
    public R customerPage(@RequestParam(value = "current", required = false) Integer current) {
        if (current == null) {
            current = 1;
        }
        PageInfo<TCustomer> pageInfo = customerService.getCustomerByPage(current);
        return R.OK(pageInfo);
    }

    /**
     * 转换客户
     * @param customerQuery
     * @param token
     * @return
     */
    @PostMapping(value = "/api/clue/customer")
    public R convertCustomer(@RequestBody CustomerQuery customerQuery, @RequestHeader("Authorization") String token) {
        customerQuery.setToken(token);
        Boolean convert = customerService.convertCustomer(customerQuery);
        return convert ? R.OK() : R.FAIL();
    }
}
